#include <stdlib.h>
#include <pthread.h>
#include <stdexcept>
#include "Thread/Lock.h"

inline pthread_rwlock_t*& v2l(void* &tHandle)
{ 
	return reinterpret_cast<pthread_rwlock_t*&>(tHandle);
};

LockImpl::LockImpl() : lHandle(NULL)
{
	lHandle = malloc(sizeof(pthread_rwlock_t));
	if((NULL != lHandle)&&(0 != pthread_rwlock_init(v2l(lHandle), NULL)))
	{
		throw std::runtime_error("Cannot init rwlock handle!");
	};
};

LockImpl::~LockImpl()
{
	if(NULL != lHandle)
	{
		pthread_rwlock_destroy(v2l(lHandle));
		free(lHandle);
	};

};

bool LockImpl::ReadLock()
{
	return (0 == pthread_rwlock_rdlock(v2l(lHandle)));
};

bool LockImpl::ReadTryLock()
{
	return (0 == pthread_rwlock_tryrdlock(v2l(lHandle)));
};

bool LockImpl::WriteLock()
{
	return (0 == pthread_rwlock_wrlock(v2l(lHandle)));
};

bool LockImpl::WriteTryLock()
{
	return (0 == pthread_rwlock_trywrlock(v2l(lHandle)));
};

bool LockImpl::UnlockLast()
{
	return (0 == pthread_rwlock_unlock(v2l(lHandle)));
};

